package com.rao.quartz.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Author: raoguang
 * @Date: 2022/05/26/23:19
 * @Description:
 */
public class JWTUtils {
    private static final String SING = "raoguang666";   //签名

    /**
     * @description: 生成token  header.payload.sing
     * @params:
     * @return:
     * @author: raoguang
     * @dateTime: 2022/5/26 23:40
     */
    public static String createToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 2000);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        //sing 签名
        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));   //sign
        return token;
    }

    /**
     * @description: 验证token
     * @params:
     * @return:
     * @author: raoguang
     * @dateTime: 2022/5/26 23:48
     */
    public static DecodedJWT verifyToken(String token) {

        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
